//
//  StudentModel.m
//  UADE-Mobile
//
//  Created by Marcos Damian Pianelli on 9/20/11.
//  Copyright (c) 2011 DG. All rights reserved.
//

#import "StudentModel.h"

@implementation StudentModel
@synthesize userHash, user, password,recordDic,records, groupDic, timestamp;



StudentModel * instance;



+(id)SharedInstance{
    
    if(instance == nil){
        instance = [[StudentModel alloc] init];
        instance.user = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
        instance.password = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
        instance.userHash = [[NSUserDefaults standardUserDefaults] objectForKey:@"hash"];
        instance.recordDic = [NSMutableDictionary dictionary];
        instance.groupDic = [NSMutableDictionary dictionary];
    }
    
    return instance;
    
}

-(void)doLogin:(id)delegate user:(NSString*)userName password:(NSString*)pass{
    
    self.user = userName;
    self.password = pass;
    [NSThread detachNewThreadSelector:@selector(login:) toTarget:self withObject:delegate];
    
}

-(void)doLogout{

    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"username"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"password"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"hash"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"notifications"];
    self.timestamp = nil;
    [self.records removeAllObjects];

}


    
-(void)login:(id)delegate{
  
    @autoreleasepool {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];

        NSString * urlStr = [NSString stringWithFormat:@"%@%@/%@",kLoginPage,self.user,self.password];
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];

        NSURLResponse *response;
        NSError *error = nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:request
                                             returningResponse:&response error:&error];
        
        if (error)
        {
            NSLog(@"%@", [error localizedDescription]);
        }
        else
        {
            NSString *result = [[NSString alloc] initWithData:data
                                                      encoding:NSUTF8StringEncoding];
            NSLog(@"%@", result);
        }
        
        //NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

        self.userHash = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]
                            stringByReplacingOccurrencesOfString:@"\"" withString:@""];
        
        NSLog(@"HASH: %@", self.userHash);
        
        if( ![self.userHash isEqualToString:@""]){
          
            [[NSUserDefaults standardUserDefaults] setObject:self.user forKey:@"username"];
            [[NSUserDefaults standardUserDefaults] setObject:self.password forKey:@"password"];
            [[NSUserDefaults standardUserDefaults] setObject:self.userHash forKey:@"hash"];

            if([delegate respondsToSelector:@selector(didLogin:)]){
                [delegate performSelectorOnMainThread:@selector(didLogin:) withObject:self waitUntilDone:FALSE];
            }
            
            
        }else{
            
            if([delegate respondsToSelector:@selector(didFailLogin:)]){
                [delegate performSelectorOnMainThread:@selector(didFailLogin:) withObject:self waitUntilDone:FALSE];
            }
        }
     
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];

    }
    
    
}



-(void)addGroupMessage:(NSString*)msg toGroup:(NSString*)groupID withDelegate:(id<StudentGroupMessageDelegate>)delegate{

    [NSThread detachNewThreadSelector:@selector(doGroupMessageAdd:) toTarget:self withObject:[NSArray arrayWithObjects:msg,groupID,delegate,nil]];

}


-(void)doGroupMessageAdd:(NSArray*)content{
    @autoreleasepool {
        
        
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
        
        id delegate = [content objectAtIndex:2];
        
        
        
        NSString * urlStr = [NSString stringWithFormat:kCommentPage,self.userHash,[content objectAtIndex:1]];
        NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"CanDoIt" forHTTPHeaderField:@"User-Agent"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:@"Host" forHTTPHeaderField:@"www.webcampus.uade.edu.ar"];

        
        NSString * filteredMsg = [NSString stringWithFormat:@"{\"Comment\":\"%@\"",
                                    [[[content objectAtIndex:0] stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""] 
                                   
                                     stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"]];
        
        NSData * httpBodyData = [filteredMsg dataUsingEncoding:NSUTF16BigEndianStringEncoding];
        
        [request setValue:@"Content-Length" forHTTPHeaderField:[NSString stringWithFormat:@"%d",[httpBodyData length]]];

        
        [request setHTTPBody:httpBodyData];
        
        NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSString * output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                         
        
        
        if([delegate respondsToSelector:@selector(didAddGroupMessage:withError:)] ){

            if( [output rangeOfString:@"true"].length != 0 ){
                [delegate didAddGroupMessage:self withError:nil];
            }else{
                  [delegate didAddGroupMessage:self withError:[NSError errorWithDomain:@"uade.com.ar" code:1 userInfo:nil]];
            }
        
        }
            
           
            
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
  
        
    }
}










-(void)fetchRecordsWithDelegate:(id)delegate{
    
    [NSThread detachNewThreadSelector:@selector(doRecordsFetch:) toTarget:self withObject:delegate];
    
}

-(BOOL)fetchEnabled{
    return TRUE;
    /*if( self.timestamp == nil)
        return TRUE;
    
    NSDate * now = [NSDate date];
    
    double minutes = [now timeIntervalSinceDate:self.timestamp]/60;
    
    return minutes >= 10? TRUE:FALSE;*/
}



-(void)doRecordsFetch:(id)delegate{
    @autoreleasepool {
       
        if( ![self fetchEnabled]){
            if([delegate respondsToSelector:@selector(didGetStudentRecords:withError:)]){
                [delegate didGetStudentRecords:self.recordDic withError:[NSError errorWithDomain:@"" code:2 userInfo:nil]];
            }
            
            return;
        }
        
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];

        NSString * urlStr = [NSString stringWithFormat:kMarksPage,self.userHash];
        
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
        
        NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSLog(@"records?");
        self.records = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] JSONValue] ;
                           

        if(self.records != nil){
            
            self.timestamp = [NSDate date];
            
            if([delegate respondsToSelector:@selector(didGetStudentRecords:withError:)]){
                [delegate didGetStudentRecords:self withError:nil];
            }
            
            
        }else{
            if([delegate respondsToSelector:@selector(didGetStudentRecords:withError:)]){
                [delegate didGetStudentRecords:self.recordDic withError:[NSError errorWithDomain:@"" code:1 userInfo:nil]];
            }
        }

        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];

    }    
   
}


#pragma Extra Info

-(void)checkVersionCompatibilityWithDelegate:(id<StudentVersionCompatibilityDelegate>)delegate{
 
    [NSThread detachNewThreadSelector:@selector(checkVersion:) toTarget:self withObject:delegate];

}

-(void)checkVersion:(id)delegate{
    @autoreleasepool {
        
    
        NSString * urlStr = [NSString stringWithFormat:kCompatibilityCheck,@"1.0",@"webcampus.iphone"];
        
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
        
        NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSLog(@"VERSION");
        NSDictionary * dic = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] JSONValue] ;

        if([delegate respondsToSelector:@selector(didGetVersionInfo:withError:)]){

            if( dic != nil){
            
                [delegate didGetVersionInfo:dic withError:nil];
            
            }else{
                [delegate didGetVersionInfo:nil withError:
                    [NSError errorWithDomain:@"webcampus.com" code:1 userInfo:nil]
                 ];
            }
        
        }
        
        
        
                
    }
}


-(void)fetchMoreInfoWithDelegate:(id)delegate aulaID:(NSString*)aulaID{
    
    
    NSDictionary * dic = [self.recordDic objectForKey:aulaID];
    
    if( dic == nil ){
        [NSThread detachNewThreadSelector:@selector(doMoreInfoFetch:) toTarget:self withObject:[NSArray arrayWithObjects:delegate,aulaID,nil] ];
    }else{
        
        if([delegate respondsToSelector:@selector(didGetMoreStudentInfo:withError:)]){
            [delegate didGetMoreStudentInfo:dic withError:nil];
        }
        

    }
    
    
    
}





-(void)doMoreInfoFetch:(NSArray*)content{
    
    @autoreleasepool {
        
        
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
        
        NSString * urlStr = [NSString stringWithFormat:kMoreInfoPage,self.userHash,[content objectAtIndex:1]];
        
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
        
        NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
       
        NSDictionary * dic = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] JSONValue] ;
        
        
        
       id delegate = [content objectAtIndex:0];
        
        if( dic != nil){
            
            [self.recordDic setObject:dic forKey:[content objectAtIndex:1]];
             
            if([delegate respondsToSelector:@selector(didGetMoreStudentInfo:withError:)]){
                [delegate didGetMoreStudentInfo:dic  withError:nil];
            }
            
            
        }else{
            
            if([delegate respondsToSelector:@selector(didGetMoreStudentInfo:withError:)]){
               [delegate didGetMoreStudentInfo:dic withError:[NSError errorWithDomain:@"" code:1 userInfo:nil]];
            }
        }
        
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
        
    }    
    
}




-(void)fetchGroupWithDelegate:(id)delegate aulaID:(NSString*)aulaID forceFetch:(BOOL)force{
    
    NSDictionary * dic = [self.groupDic objectForKey:aulaID];
    
    if( dic == nil || force == TRUE ){
        [NSThread detachNewThreadSelector:@selector(doGroupFetch:) toTarget:self withObject:[NSArray arrayWithObjects:delegate,aulaID,nil] ];
    }else{
        
        if([delegate respondsToSelector:@selector(didGetGroupInfo:withError:)]){
            [delegate didGetGroupInfo:dic withError:nil];
        }
        
        
    }
    
    
    
}




-(void)fetchGroupWithDelegate:(id)delegate aulaID:(NSString*)aulaID{
    
    
    NSDictionary * dic = [self.groupDic objectForKey:aulaID];
    
    if( dic == nil ){
        [NSThread detachNewThreadSelector:@selector(doGroupFetch:) toTarget:self withObject:[NSArray arrayWithObjects:delegate,aulaID,nil] ];
    }else{
        
        if([delegate respondsToSelector:@selector(didGetGroupInfo:withError:)]){
            [delegate didGetGroupInfo:dic withError:nil];
        }
        
        
    }
    

    
}


-(void)doGroupFetch:(NSArray*)content{
    
    @autoreleasepool {
        
        
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
        
        NSString * urlStr = [NSString stringWithFormat:kGroupPage,self.userHash,[content objectAtIndex:1]];
        
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
        
        NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
                
        NSDictionary * dic = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] JSONValue] ;
        
        
        
        id delegate = [content objectAtIndex:0];
        
        if( dic != nil){
            
            [self.groupDic setObject:dic forKey:[content objectAtIndex:1]];
            
            if([delegate respondsToSelector:@selector(didGetGroupInfo:withError:)]){
                [delegate didGetGroupInfo:dic  withError:nil];
            }
            
            
        }else{
            
            if([delegate respondsToSelector:@selector(didGetGroupInfo:withError:)]){
                [delegate didGetGroupInfo:dic withError:[NSError errorWithDomain:@"" code:1 userInfo:nil]];
            }
        }
        
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
        
    }    
    
}




@end
